package com.jues.huichain;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.azhon.appupdate.config.UpdateConfiguration;
import com.azhon.appupdate.manager.DownloadManager;
import com.blankj.rxbus.RxBus;
import com.blankj.utilcode.util.AppUtils;
import com.jues.huichain.login.entity.AppUpdataEntity;
import com.jues.huichain.login.model.EntranceModel;
import com.jues.huichain.widget.NativeTabButton;

import health.lm.com.component_base.base.event.BusProvider;
import health.lm.com.component_base.base.event.IBus;
import health.lm.com.component_base.base.event.RxBusImpl;
import health.lm.com.component_base.base.mvp.activity.XActivity;
import health.lm.com.home.fragment.HomeFragment;
import health.lm.com.network.callback.SimpleCallBack;
import health.lm.com.router.ARouterConstant;
import health.lm.com.router.RouterCenter;

/**
 * 主页
 *
 * @author GQI
 * @date 2019 /06/06
 */
@Route(path = ARouterConstant.MainActivity)
public class MainActivity extends XActivity {
    FrameLayout container;
    private Fragment mCurrentFragment;
    private NativeTabButton[] mTabButtons;
    private Fragment[] mFragments;
    private int[] checkImage = {R.drawable.tab_icon_home_ok, R.drawable.tab_icon_renmai_ok, R.drawable.tab_icon_activity_ok,
            R.drawable.tab_icon_profilt_ok};
    private int[] unCheckImage = {R.drawable.tab_icon_home_default, R.drawable.tab_icon_renmai_default, R.drawable.tab_icon_activity_default,
            R.drawable.tab_icon_profilt_default};
    private int[] title = {R.string.main_bottom_1, R.string.main_bottom_2,
            R.string.main_bottom_3, R.string.main_bottom_4};
    private NativeTabButton mNav_home;
    private NativeTabButton mNav_contacts;
    private NativeTabButton mNav_activity;
    private NativeTabButton mNav_mine;
    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public void initData(Bundle savedInstanceState) {
        container = findViewById(R.id.container);
        mNav_home = findViewById(R.id.nav_home);
        mNav_contacts = findViewById(R.id.nav_contacts);
        mNav_activity = findViewById(R.id.nav_activity);
        mNav_mine = findViewById(R.id.nav_mine);
        init();
        setFragmentShow(0);
        checkUpdata();
        //App.getModel().setAccess_token(token);
        //App.getModel().setUid(uid);
    }

    private void init() {
        mFragments = new Fragment[4];
        mFragments[0] = RouterCenter.toHome();
        mFragments[1] = RouterCenter.toContacts();
        mFragments[2] = RouterCenter.toActivity();
        mFragments[3] = RouterCenter.toMine();
        mTabButtons = new NativeTabButton[]{mNav_home, mNav_contacts, mNav_activity, mNav_mine};
        for (int i = 0; i < 4; i++) {
            mTabButtons[i].setTitle(getString(title[i]));
            mTabButtons[i].setIndex(i);
            mTabButtons[i].setSelectedImage(getResources().getDrawable(
                    checkImage[i]));
            mTabButtons[i].setUnselectedImage(getResources().getDrawable(
                    unCheckImage[i]));
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public Object newP() {
        return null;
    }

    public void setFragmentShow(int index) {
        mTabButtons[0].setSelectedButton(false);
        mTabButtons[1].setSelectedButton(false);
        mTabButtons[2].setSelectedButton(false);
        mTabButtons[3].setSelectedButton(false);
        mTabButtons[index].setSelectedButton(true);
        addFragment(R.id.container, mFragments[index]);
    }

    /**
     * 显示fragment
     *
     * @param frameLayoutId frameLayoutId
     * @param fragment      fragment
     */
    private void addFragment(int frameLayoutId, Fragment fragment) {
        if (fragment != null) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (fragment.isAdded()) {
                if (mCurrentFragment != null) {
                    transaction.hide(mCurrentFragment).show(fragment);
                } else {
                    transaction.show(fragment);
                }
            } else {
                if (mCurrentFragment != null) {
                    transaction.hide(mCurrentFragment).add(frameLayoutId, fragment);
                } else {
                    transaction.add(frameLayoutId, fragment);
                }
            }
            mCurrentFragment = fragment;
            transaction.commit();
        }
    }

    private void checkUpdata() {
        //检测APP是否有更新
        EntranceModel.getInstance().appUpdate(AppUtils.getAppVersionName()
                , new SimpleCallBack<AppUpdataEntity>() {
                    @Override
                    public void onSuccess(AppUpdataEntity entity) {
                        /*status 0无更新 1有更新*/
                        if (entity.getStatus() == 0) {
                            return;
                        }
//                        UpdateAppUtils.from(mActivity)
//                                .checkBy(UpdateAppUtils.CHECK_BY_VERSION_NAME) //更新检测方式，默认为VersionCode
//                                //.serverVersionCode(2)
//                                .serverVersionName(entity.getVersion())
//                                .apkPath(entity.getUrl())
//                                .showNotification(true) //是否显示下载进度到通知栏，默认为true
//                                .updateInfo(entity.getDesc())  //更新日志信息 String
//                                .downloadBy(UpdateAppUtils.DOWNLOAD_BY_APP) //下载方式：app下载、手机浏览器下载。默认app下载
//                                .isForce(true) //是否强制更新，默认false 强制更新情况下用户不同意更新则不能使用app
//                                .update();
                        UpdateConfiguration configuration = new UpdateConfiguration().setForcedUpgrade(true);
                        DownloadManager.getInstance(mActivity)
                                .setAuthorities("com.jues.huichain")
                                .setApkName("YJK.apk")
                                .setApkUrl(entity.getUrl())
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setShowNewerToast(true)
                                .setConfiguration(configuration)
                                .setApkVersionCode(entity.getCode())
                                .setApkVersionName(entity.getVersion())
                                //.setApkSize("20.4")
                                .setAuthorities(getPackageName())
                                .setApkDescription(entity.getDesc())
                                .download();
                    }
                });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ARouterConstant.GROWTH_JUMP_SUCCESS) {
            if (data != null) {
                int tag = data.getIntExtra(ARouterConstant.GROWTH_JUMP,1);
                //跳转到链活动
                if(tag == 2){
                    setFragmentShow(2);
                }else {
                    //跳转到首页
                    setFragmentShow(0);
                }

            }
        }
    }
}
